package 反射.reflect;

import org.junit.Test;

import java.lang.reflect.Field;

/**
 * 获取类的成员变量
 */
public class testField {
    @Test
    public void testGetFields() throws Exception {
        //1.反射第一步，得到类的Class对象
        Class c = Cat.class;
        //2.获取类的全部成员变量，
        Field[] declaredFields = c.getDeclaredFields();//获取所有成员变量
        //3.遍历成员变量数组
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField.getName()+"  "+declaredField.getType());
        }

        //4.获取某个成员变量
        Field name = c.getDeclaredField("name");
        System.out.println(name.getName()+" "+name.getType());
        Field age = c.getDeclaredField("age");
        System.out.println(age.getName()+" "+age.getType());

        //赋值
        Cat cat=new Cat();
        name.setAccessible(true);//禁止访问控制权限
        name.set(cat,"新的成员变量");

        //取值
        String name1 = (String) name.get(cat);
        System.out.println(name1);
    }
}
